import { http } from "@/utils/http";
import type { ArticleTagInfo } from "./article-tag";

/** 统一响应格式 */
export interface ApiResponse<T = any> {
  /** 状态码 */
  code: number;
  /** 响应消息 */
  message: string;
  /** 响应数据 */
  data?: T;
  /** 时间戳 */
  timestamp?: number;
}

// 用户详情相关类型定义
export interface UserStats {
  articleCount: number;
  totalViewCount: number;
  totalLikeCount: number;
  totalCommentCount: number;
  totalCollectCount: number;
  followerCount: number;
  followingCount: number;
}

export interface RecentArticle {
  id: number;
  title: string;
  summary: string;
  coverImage?: string;
  viewCount: number;
  likeCount: number;
  commentCount: number;
  collectCount: number;
  publishTime: string;
  categoryName: string;
  tagList: ArticleTagInfo[];
}

export interface UserProfile {
  userId: number;
  userName?: string; // 可选,新版API可能不返回
  nickName: string;
  email: string;
  avatar?: string;
  phonenumber?: string; // 脱敏后的手机号
  sex: string;
  sexName: string;
  signature?: string; // 个性签名
  createTime: string;
  stats: UserStats;
  recentArticles: RecentArticle[];
  isFollowed: boolean;
}

export interface Article {
  id: number;
  title: string;
  summary: string;
  coverImage?: string;
  status?: number; // 文章状态：0=草稿，1=已发布，2=已删除
  viewCount: number;
  likeCount: number;
  commentCount: number;
  collectCount: number;
  publishTime: string;
  categoryName: string;
  tagList?: ArticleTagInfo[];
}

export interface ArticleListParams {
  userId: number;
  page?: number;
  size?: number;
  status?: number;
  categoryId?: number;
  tagName?: string;
  keyword?: string;
  orderBy?: string;
  orderDirection?: "asc" | "desc";
}

export interface ArticleListResponse {
  code: number;
  message: string;
  data: any;
  records: Article[];
  total: number;
  current: number;
  size: number;
}

export interface FollowUser {
  userId: number;
  userName: string;
  nickName: string;
  avatar?: string;
  articleCount: number;
  followerCount: number;
  followTime: string;
  isFollowBack?: boolean;
}

export interface FollowParams {
  userId: number;
  isFollow: boolean;
}

// API接口函数

/**
 * 获取指定用户详情信息
 */
export const getUserProfileApi = (userId: number) => {
  return http.request<UserProfile>("get", `/api/user/${userId}/profile`);
};

/**
 * 获取当前用户详情信息
 */
export const getCurrentUserProfileApi = () => {
  return http.request<UserProfile>("get", "/api/user/profile");
};

/**
 * 分页查询用户发布的文章
 */
export const getUserArticlesApi = (params: ArticleListParams) => {
  const { userId, ...queryParams } = params;
  return http.request<ArticleListResponse>(
    "get",
    `/api/user/${userId}/articles`,
    {
      params: queryParams
    }
  );
};

/**
 * 分页参数
 */
export interface PageParams {
  page?: number;
  size?: number;
}

/**
 * 分页响应
 */
export interface PageResponse<T> {
  records: T[];
  total: number;
  size: number;
  current: number;
  pages: number;
}

/**
 * 分页获取用户粉丝列表
 * @param userId 用户ID
 * @param params 分页参数
 */
export const getUserFollowersApi = (userId: number, params?: PageParams) => {
  return http.request<PageResponse<FollowUser>>(
    "get",
    `/api/user/${userId}/followers`,
    { params }
  );
};

/**
 * 分页获取用户关注列表
 * @param userId 用户ID
 * @param params 分页参数
 */
export const getUserFollowingApi = (userId: number, params?: PageParams) => {
  return http.request<PageResponse<FollowUser>>(
    "get",
    `/api/user/${userId}/following`,
    { params }
  );
};

/**
 * 分页获取用户点赞的文章列表
 * @param userId 用户ID
 * @param params 分页参数
 */
export const getUserLikedArticlesApi = (
  userId: number,
  params?: PageParams
) => {
  return http.request<PageResponse<Article>>(
    "get",
    `/api/user/${userId}/liked-articles`,
    { params }
  );
};

/**
 * 分页获取用户收藏的文章列表
 * @param userId 用户ID
 * @param params 分页参数
 */
export const getUserCollectedArticlesApi = (
  userId: number,
  params?: PageParams
) => {
  return http.request<PageResponse<Article>>(
    "get",
    `/api/user/${userId}/collected-articles`,
    { params }
  );
};

/**
 * 文章展示查询参数
 */
export interface ArticleShowcaseParams {
  /** 页码 */
  page?: number;
  /** 每页大小 */
  size?: number;
  /** 排序类型：latest-最新，hot-最热 */
  sortType?: "latest" | "hot";
}

/**
 * 获取用户文章展示列表(支持分页和排序)
 * @param userId 用户ID
 * @param params 查询参数
 * @returns 分页的文章列表
 */
export const getUserArticleShowcaseApi = (
  userId: number,
  params?: ArticleShowcaseParams
) => {
  return http.request<ApiResponse<PageResponse<Article>>>(
    "get",
    `/api/user/${userId}/articles/showcase`,
    { params }
  );
};

/**
 * 关注/取消关注用户
 * @param userId 被关注/取消关注的用户ID
 * @param isFollow 关注状态：true-关注，false-取消关注
 * @returns 操作结果消息
 *
 * @example
 * // 关注用户
 * followUserApi({ userId: 123, isFollow: true })
 *
 * // 取消关注
 * followUserApi({ userId: 123, isFollow: false })
 */
export const followUserApi = (params: FollowParams) => {
  const { userId, isFollow } = params;
  console.log(`👥 关注API调用 - 用户ID: ${userId}, isFollow: ${isFollow}`);
  return http.request<ApiResponse<null>>("post", `/api/user/${userId}/follow`, {
    data: { isFollow } // 使用请求体传递参数
  });
};

// 工具函数

/**
 * 格式化数字显示（如：1000 -> 1k）
 */
export const formatNumber = (num: number): string => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + "M";
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + "k";
  }
  return num.toString();
};

/**
 * 格式化时间显示
 */
export const formatTime = (timeStr: string): string => {
  const time = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - time.getTime();

  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;
  const month = 30 * day;
  const year = 365 * day;

  if (diff < minute) {
    return "刚刚";
  } else if (diff < hour) {
    return Math.floor(diff / minute) + "分钟前";
  } else if (diff < day) {
    return Math.floor(diff / hour) + "小时前";
  } else if (diff < month) {
    return Math.floor(diff / day) + "天前";
  } else if (diff < year) {
    return Math.floor(diff / month) + "个月前";
  } else {
    return Math.floor(diff / year) + "年前";
  }
};

/**
 * 获取性别显示文本
 */
export const getSexText = (sex: string): string => {
  const sexMap: Record<string, string> = {
    "0": "男",
    "1": "女",
    "2": "保密"
  };
  return sexMap[sex] || "保密";
};

/**
 * 获取文章状态文本
 */
export const getArticleStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: "草稿",
    1: "已发布",
    2: "已删除"
  };
  return statusMap[status] || "未知";
};

/**
 * 获取文章状态类型（用于标签颜色）
 */
export const getArticleStatusType = (status: number): string => {
  const typeMap: Record<number, string> = {
    0: "info",
    1: "success",
    2: "danger"
  };
  return typeMap[status] || "info";
};
